import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import styles from './styles.module.css'
import clsx from 'clsx'

const Carousel = ({ slides }) => {
  const [currentSlideIndex, setCurrentSlideIndex] = useState(0)

  const nextSlide = () => {
    setCurrentSlideIndex(
      (prevIndex) => (prevIndex + 1) % slides.length
    )
  }

  const prevSlide = () => {
    setCurrentSlideIndex((prevIndex) =>
      prevIndex === 0 ? slides.length - 1 : prevIndex - 1
    )
  }

  useEffect(() => {
    const timer = setInterval(nextSlide, 3000)
    return () => clearInterval(timer)
  }, [])

  return (
    <div className={styles.carouselContainer}>
      <div className={clsx('row', styles.center)}>
        <div className={clsx('col col--1')}>
          <button
            className={`${styles.carouselButton} ${styles.leftButton}`}
            onClick={prevSlide}>
            &lt;
          </button>
        </div>
        <div className={clsx('col col--10')}>
          <div className={styles.slideContent}>
            <h1 className={styles.slideTitle}>
              {slides[currentSlideIndex].title}
            </h1>
            <p className={styles.slideText}>
              {slides[currentSlideIndex].text}
            </p>
          </div>
        </div>
        <div className={clsx('col col--1')}>
          <button
            className={`${styles.carouselButton} ${styles.rightButton}`}
            onClick={nextSlide}>
            &gt;
          </button>
        </div>
      </div>
    </div>
  )
}

Carousel.propTypes = {
  slides: PropTypes.arrayOf(
    PropTypes.shape({
      title: PropTypes.string.isRequired,
      text: PropTypes.string.isRequired,
    })
  ).isRequired,
}

export default Carousel
